package org.model.service;

import com.google.gson.Gson;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
import org.jetbrains.annotations.NotNull;
import org.model.controller.BigModelController;
import org.model.pojo.JsonParse;
import org.model.pojo.RoleContent;
import org.model.pojo.Text;
import org.model.util.BeanUtil;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;


public class modelListener extends WebSocketListener {
    public static final Gson gson = new Gson();

    public static ConcurrentHashMap<String,List<RoleContent>> historyList=new ConcurrentHashMap<>();

    private  String userID;
    public modelListener(String userID) {
        this.userID = userID;

    }

    @Override
    public void onClosing(@NotNull WebSocket webSocket, int code, @NotNull String reason) {
        super.onClosing(webSocket, code, reason);
        System.out.println(code);
    }

    @Override
    public void onOpen(WebSocket webSocket, Response response) {
        super.onOpen(webSocket, response);
        System.out.println(66666);
    }

    @Override
    public void onMessage(WebSocket webSocket, String text) {
         System.out.println(userID + "用来区分那个用户的结果" + text);
        JsonParse myJsonParse = gson.fromJson(text, JsonParse.class);
        if (myJsonParse.header.code != 0) {
            System.out.println("发生错误，错误码为：" + myJsonParse.header.code);
            System.out.println("本次请求的sid为：" + myJsonParse.header.sid);
            webSocket.close(1000, "");
        }

        List<Text> textList = myJsonParse.payload.choices.text;
        System.err.print(textList);
        for (Text temp : textList) {
            StringBuilder stringBuilder=new StringBuilder();
            stringBuilder.append(temp.getContent());
            BigModelController bean = BeanUtil.getBean(BigModelController.class);
            bean.sendOneMessage(userID,stringBuilder.toString());

        }
        if (myJsonParse.header.status == 2) {
            // 可以关闭连接，释放资源
//            webSocket.close(1000,"");
            if(canAddHistory(userID)){
                RoleContent roleContent=new RoleContent();
                roleContent.setRole("assistant");
                historyList.get(userID).add(roleContent);
            }else{
                historyList.remove(0);
                RoleContent roleContent=new RoleContent();
                roleContent.setRole("assistant");
                historyList.get(userID).add(roleContent);
            }

        }
    }

    @Override
    public void onFailure(WebSocket webSocket, Throwable t, Response response) {
        super.onFailure(webSocket, t, response);
        try {
            if (null != response) {
                int code = response.code();
                System.out.println("onFailure code:" + code);
                System.out.println("onFailure body:" + response.body().string());
                if (101 != code) {
                    System.out.println("connection failed");
                    System.exit(0);
                }
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public  boolean canAddHistory(String userID){  // 由于历史记录最大上线1.2W左右，需要判断是能能加入历史
        int history_length=0;
        for(RoleContent temp:historyList.get(userID)){
            history_length=history_length+temp.content.length();
        }
        if(history_length>12000){
            historyList.get(userID).remove(0);
            historyList.get(userID).remove(1);
            historyList.get(userID).remove(2);
            historyList.get(userID).remove(3);
            historyList.get(userID).remove(4);
            return false;
        }else{
            return true;
        }
    }

}


